package Redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

public class Rdo {

    private static final String LIGHT_KEY = "map:light";
    private static final String OBS_KEY = "map:obstacle";
    private static final String ALGORITHM_KEY = "map:alg";
    //public static Jedis jedis;
    private static JedisPool jedisPool; // 改用连接池

    public Rdo(String host, int port) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        this.jedisPool = new JedisPool(poolConfig, host, port);
    }

    public void connect() {
        try (Jedis jedis = jedisPool.getResource()) {
            String ping = jedis.ping();
            if (!"PONG".equals(ping)) {
                throw new RuntimeException("Redis connection failed");
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to connect to Redis", e);
        }
    }
    public void lpush(String key, String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.lpush(key, value);
        } catch (Exception e) {
            System.err.println("Redis lpush 操作失败: " + e.getMessage());
        }
    }
    /**
     * 连接 Redis 服务器
     *
     * @param host Redis 主机地址
     * @param port Redis 端口
     */
    /*public void connect(String host, int port) {
        // 初始化连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10); // 最大连接数
        poolConfig.setMaxIdle(5);   // 最大空闲连接
        this.jedisPool = new JedisPool(poolConfig, host, port); // 替换为实际地址和端口
        /*try {
            jedis = new Jedis(host, port);
            System.out.println("✅ 连接到 Redis 成功");
            String pingResponse = jedis.ping();
            System.out.println("Ping 响应: " + pingResponse);
        } catch (Exception e) {
            System.err.println("❌ 连接 Redis 失败: " + e.getMessage());
        }
    }*/
    /**
     * 获取车辆位置
     *
     * @param carId 车辆 ID
     * @return 车辆位置 [x, y]，如果未找到则返回 null
     */
    public static int[] getCarPosition(String carId) {
        try (Jedis jedis = jedisPool.getResource()){
            // 1. 构建 Redis Key
            String key = "car:" + carId + ":position";

            // 2. 执行 HGETALL 命令获取所有字段
            Map<String, String> fields = jedis.hgetAll(key);

            // 3. 验证数据完整性
            if (fields == null || fields.isEmpty()
                    || !fields.containsKey("x") || !fields.containsKey("y")) {
                System.out.println("警告：未找到车辆 " + carId + " 的位置信息");
                return null;
            }

            // 4. 解析坐标值
            int x = Integer.parseInt(fields.get("x"));
            int y = Integer.parseInt(fields.get("y"));

            return new int[]{x, y};
        } catch (Exception e) {
            System.err.println("Redis 读取错误：" + e.getMessage());
            return null;
        }

    }

    /**
     * 检查某个位置是否被照亮
     *
     * @param x x 坐标
     * @param y y 坐标
     * @return 如果位置被照亮返回 true，否则返回 false
     */
    public boolean checklight(int x, int y) {

        try (Jedis jedis = jedisPool.getResource()){
            int mapWidth = getMapwidth();
            int index = y * mapWidth + x;

            String lightMap = jedis.get(LIGHT_KEY);
            if (lightMap == null || lightMap.length() <= index) {
                return false; // 无数据或越界视为未照亮
            }
            return lightMap.charAt(index) == '1';
        } catch (Exception e) {
            System.err.println("Redis 读取错误：" + e.getMessage());
            return false;
        }

    }

    /**
     * 获取地图宽度
     *
     * @return 地图宽度
     */
    public int getMapwidth() {

        try(Jedis jedis = jedisPool.getResource()) {
            return Integer.parseInt(jedis.get("mapwidth"));
        } catch (Exception e) {
            System.err.println("Redis 读取错误：" + e.getMessage());
            return -1;
        }

    }

    /**
     * 获取地图高度
     *
     * @return 地图高度
     */
    public int getMapheight() {

        try(Jedis jedis = jedisPool.getResource()) {
            return Integer.parseInt(jedis.get("mapheight"));
        } catch (Exception e) {
            System.err.println("Redis 读取错误：" + e.getMessage());
            return -1;
        }

    }
    //判断是否存在这个任务
    public boolean  probe(String key)
    {
        try(Jedis jedis = jedisPool.getResource()) {
            return jedis.exists(key);
        } catch (Exception e) {
            return false;
        }
    }
    public String getalgotithm()
    {
        try(Jedis jedis = jedisPool.getResource()) {
            if(jedis.exists(ALGORITHM_KEY))
            {
                String type=jedis.get(ALGORITHM_KEY);
                if(type.equals("A*"))
                    return type;
                else if(type.equals("AA*"))
                    return type;
                else if(type.equals("BFS"))
                    return type;
                else
                    return null;
            }
            else
                return null;
        } catch (Exception e) {
            return null;
        }
    }
    //判断全图是否被照亮了
    /**
     * 获取当前已照亮的格子数量
     *
     * @return 已照亮的点数量
     */
    public long getIlluminatedCount() {
        try (Jedis jedis = jedisPool.getResource()) {
            String lightData = jedis.get(LIGHT_KEY);
            if (lightData == null || lightData.isEmpty()) {
                return 0;
            }

            // 统计 '1' 的数量
            long count = 0;
            for (char c : lightData.toCharArray()) {
                if (c == '1') {
                    count++;
                }
            }
            System.out.println("1的个数为:"+count);
            return count;
        } catch (Exception e) {
            System.err.println("读取 map:light 出错：" + e.getMessage());
            return 0;
        }
    }

    /**
     * 检查某个位置是否有障碍物
     *
     * @param x x 坐标
     * @param y y 坐标
     * @return 如果位置有障碍物返回 true，否则返回 false
     */

    public boolean checkobstacle(int x, int y) {

        try (Jedis jedis = jedisPool.getResource()){
            int mapWidth;
            int mapHeight;
            mapWidth = getMapwidth();
            mapHeight = getMapheight();
            if(x >= 0 && x < mapWidth && y >= 0 && y < mapHeight) {

            }
            else {
                return  false;
            }
            int bitIndex = y * getMapwidth() + x;
            String bits=jedis.get(OBS_KEY);
            //System.out.println(x+" "+y+"="+bits.charAt(bitIndex));
            return bits.charAt(bitIndex)=='1';
        } catch (Exception e) {
            System.err.println("Redis 读取错误：" + e.getMessage());
            return false;
        }
    }

    /**
     * 关闭连接
     */
    public void close() {
        jedisPool.close();
        /*if (jedis != null) {
            jedisPool.close();
            System.out.println("🔌 Redis 连接已关闭");
        }*/
    }
}